import store from '@/vuex/store.js'
export function formatToString(parameter, formatType, splitType) {
  var oDate
  if (typeof parameter === 'object') {
    // 传递的是Date
    oDate = parameter
  } else {
    // 传递的是秒数则转换为Date类型
    oDate = new Date(parameter)
  }
  var oYear = oDate.getFullYear()
  var oMonth = oDate.getMonth() + 1
  var oDay = oDate.getDate()
  var oHour = oDate.getHours()
  var oMin = oDate.getMinutes()
  var oSen = oDate.getSeconds()
  switch (formatType) {
    case 'Complete':
      return (oYear + splitType + getzf(oMonth) + splitType + getzf(oDay) + ' ' + getzf(oHour) + ':' + getzf(oMin) + ':' + getzf(oSen))
    case 'Simple':
      return (oYear + splitType + getzf(oMonth) + splitType + getzf(oDay))
    case 'NotSecond':
      return (oYear + splitType + getzf(oMonth) + splitType + getzf(oDay) + ' ' + getzf(oHour) + ':' + getzf(oMin))
  }
}
// 补零
function getzf (num) {
  if (parseInt(num) < 10) {
    num = '0' + num
  }
  return num
}

export function createCode () {
  let code = ''
  let codeLength = 5
  let random = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  for (var i = 0; i < codeLength; i++) {
    var index = Math.floor(Math.random() * 10)
    code += random[index]
  }
  return code
}

export function formatterDictItems(keyName, value) {
  let list = store.state.app.sysAllDictItems[keyName];
  let flag = false;
  let newValue = '';
  list.forEach(el=>{
    if(el.value == value){
      flag = true;
      newValue = el.title
    }
  });
  if(!value || !flag){
    return ''
  }else{
    return newValue
  }
}
/**
 * 过滤对象中为空的属性
 * @param obj
 * @returns {*}
 */
export function filterObj(obj) {
  if (!(typeof obj == 'object')) {
    return;
  }

  for ( let key in obj) {
    if (obj.hasOwnProperty(key)
        && (obj[key] == null || obj[key] == undefined || obj[key] === '')) {
      delete obj[key];
    }
  }
  return obj;
}
//压缩文件
export function compressImage(file, maxWidth, maxHeight, quality, callback) {
  // 创建FileReader用于读取文件
  const reader = new FileReader();

  reader.onload = function (event) {
    const img = new Image();
    img.src = event.target.result;

    img.onload = function () {
      // 创建Canvas用于压缩图片
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      const ratio = Math.min(maxWidth / img.width, maxHeight / img.height);
      const width = img.width * ratio;
      const height = img.height * ratio;

      canvas.width = width;
      canvas.height = height;
      ctx.drawImage(img, 0, 0, width, height);

      // 将Canvas的内容转换为blob，并使用FileReader读取
      canvas.toBlob(function (blob) {
        const newFile = new File([blob], file.name, { type: 'image/jpeg' });
        callback(newFile);
      }, 'image/jpeg', quality);
    };
  };

  // 读取文件内容
  reader.readAsDataURL(file);
}
